package com.weetop.cfw.mine.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.view.Gravity
import android.view.View
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.webkit.WebView
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.blankj.utilcode.util.*
import com.coorchice.library.SuperTextView
import com.gyf.immersionbar.ImmersionBar
import com.kongzue.dialog.v3.MessageDialog
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.anim.DefaultAnimator
import com.lzf.easyfloat.enums.ShowPattern
import com.lzf.easyfloat.enums.SidePattern
import com.lzf.easyfloat.interfaces.OnInvokeView
import com.trello.rxlifecycle3.android.ActivityEvent
import com.weetop.cfw.R
import com.weetop.cfw.application.CFWApplication
import com.weetop.cfw.base.presenter.imp.AudioDetailPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.view.AudioDetailView
import com.weetop.cfw.bean.AudioVideoDetailBean
import com.weetop.cfw.bean.RecommendAudioVideoBean
import com.weetop.cfw.constants.UrlConstants
import com.weetop.cfw.mine.adapter.AudioDetailAdapter
import com.weetop.cfw.utils.WebViewSettingUtils
import com.zhouyou.view.seekbar.SignSeekBar
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_audio_detail.*
import kotlinx.android.synthetic.main.layout_audio_detail_header.*
import java.util.*
import java.util.concurrent.TimeUnit


/**
 * 音频详情界面
 */
class AudioDetailActivity : CommonBaseActivity(), View.OnClickListener, AudioDetailView {

    private lateinit var audioDetailHeaderView: View

    private lateinit var audioDetailAdapter: AudioDetailAdapter
    private lateinit var textAudioImg: SuperTextView
    private lateinit var imagePauseOrPlay: ImageView
    private lateinit var audioProgressSeekBar: SignSeekBar
    private lateinit var textAudioTotalProgress: TextView
    private lateinit var textAudioCurrentProgress: TextView
    private lateinit var textAudioTitle: TextView
    private lateinit var textAudioDetailTeacherName: TextView
    private lateinit var audioDescWebView: WebView
    private lateinit var relativeAudioDesc: RelativeLayout

    private lateinit var audioDetailPresenterImp: AudioDetailPresenterImp

    private val recommendAudioBeanList = ArrayList<RecommendAudioVideoBean.DataBean>()

    private lateinit var audioDetailEasyFloatBuilder: EasyFloat.Builder

    private var dispose: Disposable? = null

    private lateinit var mediaPlayer: MediaPlayer

    private var infoId: Int = 0//音频ID

    private var audioSourceUrl: String = "http://mpge.5nd.com/2015/2015-11-26/69708/1.mp3"//音频播放地址

    override fun getLayoutId() = R.layout.activity_audio_detail

    override fun initView(savedInstanceState: Bundle?) {
        audioDetailPresenterImp = AudioDetailPresenterImp()
        audioDetailPresenterImp.attachView(this)

        audioDetailHeaderView = View.inflate(this, R.layout.layout_audio_detail_header, null)
        textAudioImg = audioDetailHeaderView.findViewById(R.id.textAudioImg)
        imagePauseOrPlay = audioDetailHeaderView.findViewById(R.id.imagePauseOrPlay)
        imagePauseOrPlay = audioDetailHeaderView.findViewById(R.id.imagePauseOrPlay)
        audioProgressSeekBar = audioDetailHeaderView.findViewById(R.id.audioProgressSeekBar)
        textAudioTotalProgress = audioDetailHeaderView.findViewById(R.id.textAudioTotalProgress)
        textAudioCurrentProgress = audioDetailHeaderView.findViewById(R.id.textAudioCurrentProgress)
        textAudioTitle = audioDetailHeaderView.findViewById(R.id.textAudioTitle)
        textAudioDetailTeacherName =
            audioDetailHeaderView.findViewById(R.id.textAudioDetailTeacherName)
        audioDescWebView = audioDetailHeaderView.findViewById(R.id.audioDescWebView)
        relativeAudioDesc = audioDetailHeaderView.findViewById(R.id.relativeAudioDesc)

        WebViewSettingUtils.initWebView(audioDescWebView)

        imagePauseOrPlay.setOnClickListener(this)
        relativeAudioDetailHeader.setOnClickListener {
            // finishActivityAndOpenFloatingWindow()
        }
        rlBack.setOnClickListener {
            finish()
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ImmersionBar.with(this).transparentStatusBar().fitsSystemWindows(true, R.color.F5F8FC)
                .statusBarDarkFont(true).init()
        } else {
            ImmersionBar.with(this).transparentStatusBar().fitsSystemWindows(true, R.color.F5F8FC)
                .statusBarDarkFont(false).init()
        }
    }

    override fun initData(savedInstanceState: Bundle?) {

        infoId = intent.getIntExtra(AUDIO_ID, 0)

        audioDetailPresenterImp.uploadUserAudioAndVideoBrowsingRecords(this, infoId.toString())

        audioDetailPresenterImp.getAudioDetailData(this, infoId)

        audioDetailAdapter =
            AudioDetailAdapter(R.layout.layout_audio_detail_item, recommendAudioBeanList)
        audioDetailAdapter.setHeaderView(audioDetailHeaderView)
        audioDetailAdapter.setOnItemClickListener { _, _, position ->
            startAudioDetailActivity(this, recommendAudioBeanList[position].infoid)
            ActivityUtils.finishActivity(this)
        }
        audioDetailRV.adapter = audioDetailAdapter

    }

    /**
     * 初始化悬浮窗
     */
    private fun initFloatingWindow(audioVideoDetailBean: AudioVideoDetailBean) {
        EasyFloat.dismissAppFloat(applicationContext)

        val mediaPlayer = MediaPlayer()

        val rotateDegrees = 10F

        audioDetailEasyFloatBuilder = EasyFloat.with(this)
            .setLayout(R.layout.layout_floating_audio, OnInvokeView {
                val textFloatingWindowLogo =
                    it.findViewById<SuperTextView>(R.id.textFloatingWindowLogo)
                textFloatingWindowLogo.setUrlImage("${UrlConstants.baseUrl}${audioVideoDetailBean.imgurl}")

                CFWApplication.isFloatingWindowFirstHide = true
                CFWApplication.audioCurrentProgress =
                    this@AudioDetailActivity.mediaPlayer.currentPosition

                mediaPlayer.setDataSource(audioSourceUrl)
                mediaPlayer.prepare()

                textFloatingWindowLogo.setOnClickListener {
                    startAudioDetailActivity(this@AudioDetailActivity, infoId)
                }

                dispose = Observable.interval(0, 1, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        textFloatingWindowLogo.rotation =
                            rotateDegrees * CFWApplication.audioFloatingWindowRotateNumber
                        val rotate = RotateAnimation(
                            0 + rotateDegrees * CFWApplication.audioFloatingWindowRotateNumber,
                            rotateDegrees * (CFWApplication.audioFloatingWindowRotateNumber + 1),
                            0.5F,
                            0.5F
                        )
                        rotate.interpolator = LinearInterpolator()
                        textFloatingWindowLogo.animation = rotate
                        textFloatingWindowLogo.animate()
                        if (CFWApplication.audioFloatingWindowRotateNumber >= 36) {
                            CFWApplication.audioFloatingWindowRotateNumber = 0
                        } else {
                            CFWApplication.audioFloatingWindowRotateNumber += 1
                        }
                    }
            })
            // 设置浮窗显示类型，默认只在当前Activity显示，可选一直显示、仅前台显示
            .setShowPattern(ShowPattern.FOREGROUND)
            .setFilter(CourseDetailActivity::class.java, AudioDetailActivity::class.java)
            .setSidePattern(SidePattern.RESULT_SIDE)
            .setGravity(Gravity.TOP or Gravity.END, -15, 100)
            // 设置Activity浮窗的出入动画，可自定义，实现相应接口即可（策略模式），无需动画直接设置为null
            .setAnimator(DefaultAnimator())
            // 浮窗的一些状态回调，如：创建结果、显示、隐藏、销毁、touchEvent、拖拽过程、拖拽结束。
            // ps：通过Kotlin DSL实现的回调，可以按需复写方法，用到哪个写哪个
            .registerCallback {
                createResult { isCreated, msg, view -> }
                show {
                    LogUtils.eTag("audioCurrentProgress", CFWApplication.audioCurrentProgress)
                    mediaPlayer.seekTo(CFWApplication.audioCurrentProgress)
                    mediaPlayer.start()
                    LogUtils.dTag("FloatingWindow", "show()")
                }
                hide {
                    if (!CFWApplication.isFloatingWindowFirstHide) {
                        CFWApplication.audioCurrentProgress = mediaPlayer.currentPosition
                    }
                    CFWApplication.isFloatingWindowFirstHide = false
                    LogUtils.dTag("FloatingWindow", "hide()")
                }
                dismiss {
                    if (dispose != null && !dispose!!.isDisposed) {
                        dispose!!.dispose()
                    }
                    mediaPlayer.release()
                    LogUtils.dTag("FloatingWindow", "dismiss()")
                }
                touchEvent { view, motionEvent -> }
                drag { view, motionEvent -> }
                dragEnd { }
            }

    }

    /**
     * 结束该界面并且打开悬浮窗
     */
    private fun finishActivityAndOpenFloatingWindow() {
        if (PermissionUtils.isGrantedDrawOverlays()) {//有悬浮窗权限
            audioDetailEasyFloatBuilder.show()
            ActivityUtils.finishActivity(this@AudioDetailActivity)
        } else {//没有悬浮窗权限
            MessageDialog.show(
                this@AudioDetailActivity,
                "提示",
                "只有开启悬浮窗权限才能使用小窗音频播放，是否前往开启悬浮窗权限？",
                "去开启",
                "暂不开启"
            ).setOnOkButtonClickListener { baseDialog, v ->
                //请求悬浮窗权限
                PermissionUtils.requestDrawOverlays(object : PermissionUtils.SimpleCallback {
                    override fun onGranted() {
                        audioDetailEasyFloatBuilder.show()
                        ActivityUtils.finishActivity(this@AudioDetailActivity)
                    }

                    override fun onDenied() {
                        ToastUtils.showLong("悬浮窗权限已拒绝，无法进行小窗播放音频")
                    }
                })
                true
            }.setOnCancelButtonClickListener { baseDialog, v ->
                ActivityUtils.finishActivity(this@AudioDetailActivity)
                true
            }
        }

    }

//    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//        if(keyCode == KeyEvent.KEYCODE_BACK){   471794653
//            //finishActivityAndOpenFloatingWindow()
//            return true
//        }
//        return super.onKeyDown(keyCode, event)
//    }

    @SuppressLint("CheckResult")
    private fun initMediaPlay(audioVideoDetailBean: AudioVideoDetailBean) {
        mediaPlayer = MediaPlayer()
        mediaPlayer.setDataSource(audioSourceUrl)
        mediaPlayer.prepare()
        audioProgressSeekBar.configBuilder.max(mediaPlayer.duration.toFloat()).min(0F).build()

        textAudioTotalProgress.text =
            TimeUtils.date2String(Date(mediaPlayer.duration.toLong()), "mm:ss")

        Observable.interval(0, 1, TimeUnit.SECONDS)
            .compose(bindUntilEvent(ActivityEvent.DESTROY))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                audioProgressSeekBar.setProgress(mediaPlayer.currentPosition.toFloat())
                textAudioCurrentProgress.text =
                    TimeUtils.date2String(Date(mediaPlayer.currentPosition.toLong()), "mm:ss")
            }
        audioProgressSeekBar.setOnProgressChangedListener(object :
            SignSeekBar.OnProgressChangedListener {
            override fun onProgressChanged(
                signSeekBar: SignSeekBar?,
                progress: Int,
                progressFloat: Float,
                fromUser: Boolean
            ) {
                if (fromUser) {
                    mediaPlayer.seekTo(progress)
                }
            }

            override fun getProgressOnActionUp(
                signSeekBar: SignSeekBar?,
                progress: Int,
                progressFloat: Float
            ) {

            }

            override fun getProgressOnFinally(
                signSeekBar: SignSeekBar?,
                progress: Int,
                progressFloat: Float,
                fromUser: Boolean
            ) {

            }
        })

        if (CFWApplication.audioCurrentProgress > 0) {
            mediaPlayer.seekTo(CFWApplication.audioCurrentProgress)//跳转到指定位置开始播放音乐
            imagePauseOrPlay.setImageResource(R.mipmap.play)//设置为正在播放的音乐图标
            mediaPlayer.start()//开始播放
            audioProgressSeekBar.setProgress(CFWApplication.audioCurrentProgress.toFloat())//设置播放进度条
            CFWApplication.audioCurrentProgress = 0//将记录的进度设置为0
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.release()
        WebViewSettingUtils.destoryWebView(audioDescWebView, relativeAudioDesc)
        audioDetailPresenterImp.detachView()
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.imagePauseOrPlay -> {
                if (mediaPlayer.isPlaying) {
                    imagePauseOrPlay.setImageResource(R.mipmap.pause_logo)
                    mediaPlayer.pause()
                } else {
                    imagePauseOrPlay.setImageResource(R.mipmap.play)
                    mediaPlayer.start()
                }
            }
        }
    }

    /**
     * 音频详情数据获取成功
     */
    override fun audioDetailDataGetSuccess(audioVideoDetailBean: AudioVideoDetailBean?) {
        if (audioVideoDetailBean != null) {
            textAudioImg.setUrlImage("${UrlConstants.baseUrl}${audioVideoDetailBean.imgurl}")
            textAudioTitle.text = audioVideoDetailBean.title
            textAudioDetailTeacherName.text = audioVideoDetailBean.author
            textAudioDetailPlayNumber.text = "${audioVideoDetailBean.playnum}次播放"
            audioDescWebView.loadData(
                Html.fromHtml(audioVideoDetailBean.content).toString(),
                "text/html; charset=UTF-8",
                null
            )
            audioSourceUrl = "${UrlConstants.baseUrl}Upload/File/${audioVideoDetailBean.furl}"
            initMediaPlay(audioVideoDetailBean)
            //  initFloatingWindow(audioVideoDetailBean)

        }
    }

    companion object {
        private const val AUDIO_ID = "AUDIO_ID"
        private const val CLASS_ID = "CLASS_ID"

        fun startAudioDetailActivity(context: Context, audioId: Int) {
            val intent = Intent(context, AudioDetailActivity::class.java)
            intent.putExtra(AUDIO_ID, audioId)
            ActivityUtils.startActivity(intent)
        }
    }

}
